package com.chensi.admin.shop.service.impl;

import com.chensi.admin.shop.common.BaseErrorCode;
import com.chensi.admin.shop.domain.Navigation;
import com.chensi.admin.shop.service.NavigationService;
import com.chensi.admin.shop.util.BeanUtils;
import com.chensi.admin.shop.dao.NavigationRepository;
import com.chensi.admin.shop.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @author si.chen
 * @date 2019/7/19 9:06
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class NavigationServiceImpl implements NavigationService {

    private final NavigationRepository navigationRepository;

    @Autowired
    public NavigationServiceImpl(NavigationRepository navigationRepository) {
        this.navigationRepository = navigationRepository;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Navigation entity) throws BaseException {
        navigationRepository.save(entity);
    }

    @Override
    public List<Navigation> list() throws BaseException {
        Sort sort = new Sort(Sort.Direction.ASC, "sort");
        return navigationRepository.findAll(sort);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Navigation navigation) throws BaseException {
        Navigation entity = this.get(navigation.getId());
        BeanUtils.copyNotNullProperties(navigation, entity);
        navigationRepository.save(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) throws BaseException {
        navigationRepository.deleteById(id);
    }

    @Override
    public Navigation get(String id) throws BaseException {
        Optional<Navigation> optional = navigationRepository.findById(id);
        return optional.orElseThrow(() -> new BaseException(BaseErrorCode.ITEM_NOT_FOUND));
    }
}
